package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.business.api.*;
import cn.wolfcode.wolf2w.business.api.domain.*;
import cn.wolfcode.wolf2w.business.query.SearchQuery;
import cn.wolfcode.wolf2w.business.repository.DestinationEsRepository;
import cn.wolfcode.wolf2w.business.repository.NoteEsRepository;
import cn.wolfcode.wolf2w.business.repository.StrategyEsRepository;
import cn.wolfcode.wolf2w.business.repository.UserEsRepository;
import cn.wolfcode.wolf2w.business.service.ISearchService;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : 邓风来
 * @date : 2025/9/24 9:53
 */
@Component

public class SearchServiceImpl implements ISearchService {

    @Autowired
    private StrategyEsRepository strategyEsRepository;
    @Autowired
    private UserEsRepository userEsRepository;
    //用于执行复杂的查询,比如高亮查询
    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private RemoteStrategyService strategyService;
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;
    @Autowired
    private RemoteNoteService remoteNoteService;
    @Autowired
    private NoteEsRepository noteEsRepository;
    @Autowired
    private DestinationEsRepository destinationEsRepository;

    @Autowired
    private RemoteDestinationService remoteDestinationService;
    @Override
    public void saveStrategy(StrategyEs strategyEs) {
        strategyEsRepository.save(strategyEs);
    }

    @Override
    public void saveDestination(DestinationEs destinationEs) {
        destinationEsRepository.save(destinationEs);
    }

    @Override
    public void saveNote(NoteEs noteEs) {
        noteEsRepository.save(noteEs);
    }

    @Override
    public void saveUser(UserEs userEs) {
        userEsRepository.save(userEs);
    }

    @Override
    public <T> Page<T> searchWithHighlight(Class<T> clazz, Class<?> esClazz, SearchQuery qo, String... column) throws InvocationTargetException, IllegalAccessException {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(
                //设置查询条件
                QueryBuilders.multiMatchQuery(qo.getKeyword(),column)
        );
        //设置分页条件
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        queryBuilder.withPageable(pageable);
        //设置高亮条件
        List<HighlightBuilder.Field> fs = new ArrayList<>();
        for (String name : column) {
            HighlightBuilder.Field field = new HighlightBuilder.Field(name);
            field.preTags("<span style='color:red'>").postTags("</span>");
            fs.add(field);
        }
        queryBuilder.withHighlightFields(fs);

        //执行查询
        List<T> list = new ArrayList<>();

        SearchHits<?> hits = template.search(queryBuilder.build(), esClazz);
        long totalHits = hits.getTotalHits();
        for (SearchHit<?> searchHit : hits.getSearchHits()) {
            Long id = Long.valueOf(searchHit.getId());
            T t = null; //用于存储mysql中的对象
            if (clazz == Strategy.class){
                t = (T)strategyService.getOne(id, SecurityConstants.INNER).getData();
            }else  if (clazz== UserInfo.class){
                t =(T)remoteUserInfoService.getOne(id,SecurityConstants.INNER).getData();
            }else if (clazz == Note.class){
                t =(T)remoteNoteService.getOne(id,SecurityConstants.INNER).getData();
            }else if (clazz == Destination.class){
                t =(T)remoteDestinationService.getOne(id,SecurityConstants.INNER).getData();
            }
            list.add(t);
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            for (String key : highlightFields.keySet()) {
                List<String> arr = highlightFields.get(key);
                StringBuffer sb = new StringBuffer();
                for (String s : arr) {
                    sb.append(s).append(" ");
                }
                String value = sb.toString();
                //commons库里面 设置t对象的key属性为value值
                BeanUtils.setProperty(t,key,value);
            }

        }
        return new PageImpl<>(list,pageable,totalHits);
    }


}
